from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver


# 用户信息扩展表
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    contact_info = models.CharField(max_length=255, blank=True, null=True, verbose_name="联系方式")
    bio = models.TextField(blank=True, null=True, verbose_name="个人简介")
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name="手机号")
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True, verbose_name="头像")

    def __str__(self):
        return self.user.username
    
    def set_password(self, password):
        """设置用户密码"""
        self.user.set_password(password)
        self.user.save()


@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserProfile.objects.create(user=instance)


@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    try:
        instance.userprofile.save()
    except UserProfile.DoesNotExist:
        UserProfile.objects.create(user=instance)


# 商品信息表
class Product(models.Model):
    CATEGORY_CHOICES = [
        ('电子产品', '电子产品'),
        ('家居生活', '家居生活'),
        ('服装鞋包', '服装鞋包'),
        ('图书文具', '图书文具'),
        ('其他', '其他'),
    ]

    STATUS_CHOICES = [
        ('在售', '在售'),
        ('已售', '已售'),
        ('下架', '下架'),
    ]

    name = models.CharField(max_length=200, verbose_name="商品名称")
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="价格")
    original_price = models.DecimalField(max_digits=10, decimal_places=2, blank=True, null=True, verbose_name="原价")

    category = models.CharField(
        max_length=20,
        choices=CATEGORY_CHOICES,
        default='其他',
        verbose_name="类别"
    )

    condition = models.CharField(max_length=20, verbose_name="成色")

    description = models.TextField(verbose_name="商品描述")

    status = models.CharField(
        max_length=10,
        choices=STATUS_CHOICES,
        default='在售',
        verbose_name="销售状态"
    )

    location = models.CharField(max_length=100, blank=True, null=True, verbose_name="所在地")

    seller = models.ForeignKey(User, on_delete=models.CASCADE, related_name='products', verbose_name="卖家")

    created_at = models.DateTimeField(auto_now_add=True, verbose_name="发布时间")

    def __str__(self):
        return self.name


# 商品图片表，与Product表建立外键关系，实现多图功能
class ProductImage(models.Model):
    product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE)
    image = models.ImageField(upload_to='product_images/')


# 购物车模型
class Cart(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='cart', verbose_name="用户")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")

    def __str__(self):
        return f"购物车：{self.user.username}"


# 购物车商品项模型
class CartItem(models.Model):
    cart = models.ForeignKey(Cart, on_delete=models.CASCADE, related_name='items', verbose_name="购物车")
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="商品")
    quantity = models.PositiveIntegerField(default=1, verbose_name="数量")

    class Meta:
        # 确保一个购物车中同一个商品只有一条记录
        unique_together = ('cart', 'product')

    def __str__(self):
        return f"{self.product.name} (数量: {self.quantity})"


# 订单模型
class Order(models.Model):
    STATUS_CHOICES = [
        ('待付款', '待付款'),
        ('已付款', '已付款'),
        ('已发货', '已发货'),
        ('已完成', '已完成'),
        ('已取消', '已取消'),
    ]

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders', verbose_name="用户")
    total_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单总价")
    status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='待付款', verbose_name="订单状态")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    # 收货地址信息，可以根据需要扩展
    shipping_address = models.CharField(max_length=255, verbose_name="收货地址", blank=True, null=True)

    def __str__(self):
        return f"订单号：{self.id} - 用户：{self.user.username}"


# 订单商品项模型
class OrderItem(models.Model):
    order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='items', verbose_name="订单")
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name="商品")
    quantity = models.PositiveIntegerField(verbose_name="数量")
    price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="购买时价格")

    def __str__(self):
        return f"{self.product.name} - 数量：{self.quantity}"